package cn.dlc.com.consumer.controller;

import cn.dlc.com.consumer.feign.ProductService;
import cn.dlc.com.nacos.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author 邓立川
 * @date 2020/12/30 14:01
 * @desc 添加当前类的描述信息
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient client;

    @Autowired
    private ProductService productService;

    @GetMapping("{id}")
    public User getUserBase(@PathVariable("id") String id) {
        List<ServiceInstance> serverList = client.getInstances("product_server");
        ServiceInstance serviceInstance = serverList.get(0);

        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + id;
        System.out.println(url);

        User user = restTemplate.getForObject(url, User.class);

        return user;
    }

    @GetMapping("nacos/{id}")
    public User getUserNacos(@PathVariable("id") String id) {

        // 整合ribbon之后的url
        String url = "http://product-server/product/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    @GetMapping("feign/{id}")
    public User getUserFeign(@PathVariable("id") String id) {
        User user = productService.getUser(id);
        return user;
    }



}
